package com.javaex.book.dao.impl;

import java.util.List;

import com.javaex.book.dao.UserDao;
import com.javaex.book.pojo.User;

public class UserDaoImpl extends BaseDao implements UserDao {
	
	@Override
	public User queryUserByUsernameOrEmail(String username, String email) {
		String sql = "SELECT id, username, age, gender, password, email, createTime FROM user WHERE username = ? OR email = ?";
		return findOne(sql, User.class, new Object[] { username, email });
	}

	@Override
	public User queryUserByUsername(String username) {
		String sql = "SELECT id, username, age, gender, password, email, createTime FROM user WHERE username = ?";
		return findOne(sql, User.class, new Object[] { username });
	}

	@Override
	public Integer saveUser(User user) {
		String sql = "INSERT INTO user(username, age, gender, password, email) VALUES(?, ?, ?, ?, ?)";
		return execute(sql, user);
	}

	@Override
	public Integer countUsers() {
		String sql = "select count(*) from user";
		return count(sql, null);
	}
	
	@Override
	public List<User> queryUserList(Integer start, Integer pageSize) {
		String sql = "select id, username, age, gender, password, email, createTime from user limit ?, ?";
		return findMany(sql, User.class, new Object[] { start, pageSize });
	}
	
	@Override
	public Integer updateUser(User user) {
		String sql = "update user set username = ?, age = ?, gender = ?, email = ? where id = ?";
		if (user.getPassword() != null && !user.getPassword().isEmpty()) {
			sql = "update user set username = ?, age = ?, gender = ?, password = ?, email = ? where id = ?";
		}
		return execute(sql, user);
	}
	
	@Override
	public User queryUserById(Integer id) {
		String sql = "select id, username, age, gender, password, email, createTime from user where id = ?";
		return findOne(sql, User.class, new Object[] { id });
	}
	
	@Override
	public Integer deleteUser(Integer id) {
		String sql = "delete from user where id = ?";
		return execute(sql, new Object[] { id });
	}
}
